package cn.jcet.gumall.ware.service.impl;

import cn.jcet.common.utils.R;
import cn.jcet.gumall.ware.fegin.ProductFigenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jcet.common.utils.PageUtils;
import cn.jcet.common.utils.Query;

import cn.jcet.gumall.ware.dao.WareSkuDao;
import cn.jcet.gumall.ware.entity.WareSkuEntity;
import cn.jcet.gumall.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFigenService productFigenService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        /**
         * skuId:
         * wareId:
         */
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper

        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        List<WareSkuEntity> skuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("sku_id", wareId));
        if (skuEntities == null || skuEntities.size() ==0){
            // 保存
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            // TODO 远程调用SKU名称
            R info = productFigenService.info(skuId);
            try {
                Map<String,Object> date = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0){
                    wareSkuEntity.setSkuName((String) date.get("skuName"));
                }
            }catch (Exception e){

            }
            // 添加库存信息
            this.baseMapper.insert(wareSkuEntity);
        }else {
            // 修改库存信息
            this.wareSkuDao.updateStock(skuId,wareId,skuNum);
        }
    }
}